// https://threejs.org/docs/index.html#api/zh/geometries/TubeGeometry
import { 
  Color,
  DoubleSide,
  LineSegments,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera, 
  Scene, 
  SphereGeometry, 
  WebGLRenderer, 
  WireframeGeometry, 
  Group,
  Vector3,
  Texture,
  TubeGeometry,
  CatmullRomCurve3,
  TextureLoader,
  RepeatWrapping,
  AdditiveBlending
} from 'three'
import stats from '../../utils/stats'
import { GUI } from 'dat.gui'
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'

const scene = new Scene()
const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(0, 60, 120)
camera.lookAt(0, 0, 0)

const peppaTexture = new TextureLoader().load('/img/peppa.png');
console.log(peppaTexture)
// peppaTexture.repeat.set(20, 1)
const matertial = new MeshBasicMaterial({
  transparent: true,
  map: peppaTexture
});
(matertial.map as Texture).wrapS = RepeatWrapping;
(matertial.map as Texture).wrapT = RepeatWrapping;
(matertial.map as Texture).repeat.set(20, 1);
let curveLength = 0;

const controls = {
  animate: true,
  color: matertial.color.getStyle(),
  numberOfPoints: 4,
  points: [],
  segments: 100,
  repeatX: 20,
  repeatY: 1,

  newPoints() {
    let points = []

    for (let i = 0; i < this.numberOfPoints; i++) {
      let x = -20 + Math.round(Math.random() * 50)
      let y = -15 + Math.round(Math.random() * 40)
      let z = -20 + Math.round(Math.random() * 40)
      points.push(new Vector3(x, y, z))
    }

    (this.points as Vector3[]) = points
  },

  redraw() {
    this.newPoints()
    generatePoints()
  }
}
let group: Group
controls.redraw()

const gui = new GUI()
gui.add(controls, 'animate').name('动画')
gui.add(controls, 'segments', 1, 300, 1).onChange(generatePoints)
gui.add(controls, 'numberOfPoints', 2, 30, 1).onChange(controls.redraw.bind(controls))
gui.addColor(controls, 'color').onChange(e => {
  matertial.color.set(new Color(e))
})
const repeatGUI = gui.addFolder('重复')
repeatGUI.add(controls, 'repeatX', 1, 20, 1).name('X').onChange(val => {
  (matertial.map as Texture).repeat.set(val, controls.repeatY);
})
repeatGUI.add(controls, 'repeatY', 1, 20, 1).name('Y').onChange(y => {
  (matertial.map as Texture).repeat.set(controls.repeatY, y);
})
repeatGUI.open()

const renderer = new WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.setClearColor(0x0099ff)

document.body.appendChild(renderer.domElement)
const trackballControls = new TrackballControls(camera, renderer.domElement)

function render() {
  stats.update()
  trackballControls.update()

  if (controls.animate) {
    group.rotation.y += 0.01
  }
  // 管道前移
  peppaTexture.offset.x -= 0.01;
  // 管道上移
  peppaTexture.offset.y -= 0.01
  
  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

render()


function generatePoints() {
  if (group) scene.remove(group)

  group = new Group()

  let pointMatertial = new MeshBasicMaterial({
    color: 0xff0000,
    transparent: false,
  })

  controls.points.forEach(point => {
    let geom = new SphereGeometry(0.2)
    let mesh = new Mesh(geom, pointMatertial)
    mesh.position.copy(point)
    group.add(mesh)
  })
  let curve = new CatmullRomCurve3(controls.points)

  let geometry = new TubeGeometry(
    // 一个由基类Curve继承而来的3D路径。
    curve,
    // 组成这一管道的分段数，默认值为64 越多过滤越平滑
    controls.segments, 
  )
  curveLength = curve.getLength()
  const shape = new Mesh(geometry, matertial)
  group.add(shape)

  const wireFrame = new WireframeGeometry(geometry)
  const lines = new LineSegments(wireFrame)
  group.add(lines)

  scene.add(group)
}